/*
** fileconf.c for  in /home/renard_g/Dropbox/epitech/dev/projets/systemunix/zappy/zappy-2015-2014s-renard_g/serv-src
**
** Made by guillaume renard
** Login   <renard_g@epitech.net>
**
** Started on  Thu Jun 07 13:17:31 2012 guillaume renard
** Last update Thu Jul 19 17:36:23 2012 pierrick druart
*/

#include	 <stdio.h>
#include	 <sys/types.h>
#include	 <sys/stat.h>
#include	 <fcntl.h>
#include	 <stdlib.h>
#include	 <string.h>

#include	 "server.h"
#include	 "fileconf.h"

static int	*check_ress(int *ress)
{
  int		check;

  check = 0;
  check += ress[FOOD];
  check += ress[LINEMATE];
  check += ress[DERAUMERE];
  check += ress[SIBUR];
  check += ress[MENDIANE];
  check += ress[PHIRAS];
  check += ress[THYSTAME];
  if (check != 100)
  {
    ress[FOOD] = 50;
    ress[LINEMATE] = 20;
    ress[DERAUMERE] = 12;
    ress[SIBUR] = 8;
    ress[MENDIANE] = 5;
    ress[PHIRAS] = 3;
    ress[THYSTAME] = 2;
  }
  return (ress);
}

static int	*thystameSpawn(char *line, int *ress)
{
  ress[THYSTAME] = atoi(line);
  return (ress);
}

static int	*foodSpawn(char *line, int *ress)
{
  ress[FOOD] = atoi(line);
  return (ress);
}

static int	*checkLine(char *line, int *ress, int i)
{
  char		**tabline;
  t_fct		tab[] =
  {{"linemate", lineMatSpawn},
    {"deraumere", deraumereSpawn},
    {"sibur", siburSpawn},
    {"mendiane", mendianeSpawn},
    {"phiras", phirasSpawn},
    {"thystame", thystameSpawn},
    {"food", foodSpawn},
    {NULL, NULL}
  };

  tabline = getTab(line, ' ');
  while (tab[i].fct)
  {
    if (!strcmp(tabline[0], tab[i].cmp))
    {
      if (tabline[1] != NULL)
	tab[i].fct(tabline[1], ress);
      break;
    }
    i++;
  }
  freetab(tabline);
  return (ress);
}

int		*getConf()
{
  FILE		*fd;
  char		*line;
  size_t	len;
  int		*ress;
  int		i;

  ress = xcalloc(NB_OBJECT, sizeof(int));
  if ((fd = xfopen("./file/conf", "r")) != NULL)
  {
    line = NULL;
    len = 0;
    while (getline(&line, &len, fd) != -1)
    {
      i = 0;
      checkLine(line, ress, i);
    }
    free(line);
    xfclose(fd);
  }
  check_ress(ress);
  printf("SPAWNRATE :\nfood : %d - linemate %d - sibur %d\
      \nmendiane %d- phiras %d - thystame %d\n\n",
      ress[FOOD], ress[LINEMATE], ress[SIBUR], ress[MENDIANE],
      ress[PHIRAS], ress[THYSTAME]);
  return (ress);
}
